<template>
  <a-modal
      :visible="visible"
      title="发布新商品"
      @ok="handleOk"
      @cancel="handleCancel"
      :confirmLoading="confirmLoading"
  >
    <a-form :model="formState" :rules="rules" ref="formRef">
      <a-form-item name="name" label="商品名称">
        <a-input v-model:value="formState.name"/>
      </a-form-item>
      <a-form-item name="price" label="价格">
        <a-input-number v-model:value="formState.price" :min="0" :step="0.01" style="width: 100%;"/>
      </a-form-item>
      <a-form-item name="description" label="商品描述">
        <a-input v-model:value="formState.description"/>
      </a-form-item>
      <a-form-item name="image" label="商品图片">
        <a-upload
            v-model:fileList="formState.fileList"
            action="/api/upload"
            list-type="picture-card"
            :before-upload="beforeUpload"
        >
          <div v-if="formState.fileList.length < 1">
            <plus-outlined/>
            <div style="margin-top: 8px">上传</div>
          </div>
        </a-upload>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import {ref, reactive} from 'vue';
import {message} from 'ant-design-vue';
import {PlusOutlined} from '@ant-design/icons-vue';
import {useProductStore, useUserStore} from "@/stores/index.js";

const emit = defineEmits(['update:visible', 'success']);

const formRef = ref();
const confirmLoading = ref(false);

const formState = reactive({
  name: '',
  price: 0,
  description: '',
  descStatus: '在售',
  fileList: [],
});

const rules = {
  name: [{required: true, message: '请输入商品名称'}],
  price: [{required: true, message: '请输入商品价格'}],
  description: [{required: true, message:'请输入商品描述'}]
};

const userStore = useUserStore();
const productStore = useProductStore();

const resetForm = () => {
  formRef.value.resetFields();
};

const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('只能上传JPG或PNG格式的图片！');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过2MB！');
  }
  return isJpgOrPng && isLt2M;
};

const handleOk = async () => {
  const userId = userStore.userInfo ? userStore.userInfo.userId : null;
  if (userId && formState) {
    const success = await productStore.publishProducts(formState, userId);
    if (success) {
      message.success("发布成功");
      emit('update:visible', false);
    } else {
      console.log("获取商品数据失败", productStore.error);
    }
  } else {
    console.log('用户ID为空啊');
  }
};

const handleCancel = () => {
  resetForm();
  emit('update:visible', false);
};
</script>

